package com.cg.bank.util;

import com.cg.bank.domain.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserBeanHandler implements ResultSetHander<User> {
    @Override
    public User handle(ResultSet resultSet) throws SQLException {
        if (!resultSet.next()){
            return null;
        }

        int resultCount = resultSet.getMetaData().getColumnCount();
        List<String> columnCountList = new ArrayList<>();
        for (int i = 1; i <= resultCount; i++) {
            // 如未指定SQL AS，getColumnLabel与getColumnName方法返回的值相同
            columnCountList.add(resultSet.getMetaData().getColumnLabel(i));
        }

        return processORM(resultSet,columnCountList);
    }

    /**
     * 处理对象关系映射
     *
     * @param resultSet 结果集
     * @param columnCountList 封装字段名list
     * @return user basic information 用户基本信息
     * @throws SQLException sql异常
     */
    private User processORM(ResultSet resultSet, List<String> columnCountList) throws SQLException {
        User user = new User();
        int resultCount = columnCountList.size();
        // 获取多行查询结果
        if (resultCount == 10) {
            // 封装用户基本信息(ID,账户，用户名(昵称)，密码,余额，年龄，性别，开户时间,头像信息)
            user.setId(resultSet.getInt(columnCountList.get(0)));
            user.setAccount(resultSet.getString(columnCountList.get(1)));
            user.setUserName(resultSet.getString(columnCountList.get(2)));
            user.setPassword(resultSet.getString(columnCountList.get(3)));
            user.setBalance(resultSet.getDouble(columnCountList.get(4)));
            user.setMail(resultSet.getString(columnCountList.get(5)));
            user.setSex(resultSet.getString(columnCountList.get(6)));
            user.setAge(resultSet.getInt(columnCountList.get(7)));
            user.setCreateTime(resultSet.getDate(columnCountList.get(8)));
            user.setImage(resultSet.getString(columnCountList.get(9)));
        } else if (resultCount == 1) {
            // 获取单行查询结果
            if ("balance".equals(columnCountList.get(0))){
                user.setBalance(resultSet.getDouble(columnCountList.get(0)));
            }
        }

        return  user;
    }

}